package com.fanghaoran.view.manager;

import com.fanghaoran.controller.ManagerController;
import com.fanghaoran.view.user.BackGroundPanel;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.io.File;
import java.io.IOException;

/**
 * @Author: win11
 * @Date: 2023/03/28/21:10
 * @Description: 添加单词书页面
 */
public class AddBookFrame extends JFrame {
    public AddBookFrame() throws Exception {
        //最外层界面frame的设置
        initFrame();
        //界面中的视图,控件等的设置
        initView();

        //设置可见
        this.setVisible(true);
    }

    private void initView() throws IOException {
        //panel来放组件
        BackGroundPanel panel = new BackGroundPanel(ImageIO.read(new File("src//image//rBackground.jpg")));
        //用垂直box实现组件垂直排列
        Box vBox = Box.createVerticalBox();
        vBox.add(Box.createVerticalStrut(100));

        Box box2 = Box.createHorizontalBox();
        //单词书名文本
        JLabel bookNameText = new JLabel("单词书名:");
        //输入框
        JTextField bookName = new JTextField(20);
        //添加到box
        box2.add(bookNameText);
        box2.add(Box.createHorizontalStrut(20));
        box2.add(bookName);

        Box box3 = Box.createHorizontalBox();
        JButton addBtn = new JButton("添加");
        box3.add(addBtn);
        //按钮点击事件
        addBtn.addActionListener(e -> {
                    String result = null;
                    try {
                        result = new ManagerController().insertBook(bookName.getText()).getResult();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    //对返回结果进行图形化提示
                    if ("输入为空".equals(result)) {
                        JOptionPane.showMessageDialog(panel, "输入不能为空");
                    } else if ("该书已存在".equals(result)) {
                        JOptionPane.showMessageDialog(panel, "该书已存在");
                    } else {
                        JOptionPane.showMessageDialog(panel, "添加成功");
                        //关闭当前页面
                        this.dispose();
                    }
                }
        );


        vBox.add(Box.createVerticalStrut(30));
        vBox.add(box2);
        vBox.add(Box.createVerticalStrut(30));
        vBox.add(box3);

        panel.add(vBox);

        this.add(panel);
    }

    private void initFrame() throws IOException {
        //设置宽高
        this.setSize(400, 400);
        //设置居中
        this.setLocationRelativeTo(null);
        //设置标题
        this.setTitle("扇贝单词");
        //设置标题旁边的logo图标
        this.setIconImage(ImageIO.read(new File("src//image//logo.jpg")));
        //设置置顶
        this.setAlwaysOnTop(true);
        //设置关闭模式
        this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    }
}
